<?php
/*
v0.03
bach
2016-12-21
sms($demand,$data)
email($demand,$data)
qrcode($url,$level,$size)
excelSimple($data)
getIpData();
*/

namespace Common\Model;
use Think\Model;
class SupportModel extends Model {

    protected $autoCheckFields = false;//关闭检测字段
    private $config;
    private function getConfig($demand){
      if(!$demand){
        return false;// 
      }
      if($this->config[$demand]){
        return $this->config[$demand];
      }
      $file_path = C('CONFIG_PATH')."/support.$demand.config.php";
      $config = file_get_contents($file_path);
      $config = substr($config, 15);
      $config = preg_replace("/\/\*[\s\S]+?\*\//", "", $config) ;
      $config = json_decode( $config, true);
      $this->config[$demand] = $config;
      return $config;
    }
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------
    // ------------------------ EMAIL ----------------------------

    private function emailSend_hongyanche($demand,$data){
      $to = $data[email];
      $userName = $data[userName];
      $title = $data[title];
      $template = $data[template];
      //开始启用hongyanche肥皂结构发送
      header("content-type:text ml;charset=utf-8");
      $client = new \SoapClient("http://ws.sih.cq.cn/sihwebservice/sendmail/sendmail.asmx?wsdl");
      $send = array(
        'key'=>"89418D76-0BB7-4311-B8EC-C3B79F6978C0",
        'strReceiver'=>$to,
        'strSubject'=>$title,
        'strContent'=>$template
        );
      $return = $client->SendEmailWithHtml($send);
      $return = json_decode(json_encode($return),1);
      $reason = $return[SendMessageResult][reason];
      if( strstr($reason,$tel) ){
        $ret = array(state=>1,errormsg=>'sms send success');
      }else{
        $ret = array(state=>0,errormsg=>$reason,data=>$return);

      }
      return $ret;
    }
    private function emailSend_alimail($demand,$data){
      $to = $data[email];
      $userName = $data[userName];
      $title = $data[title];
      $template = $data[template];
      vendor('PHPMailer');
      $email_config = C('EMAIL');
      if($data[emailname]){
        $email_config[emailname] = $data[MAIL_FROMNAME];
      }
      $mail = new \PHPMailer;
      $mail->IsSMTP();                        // 启用SMTP
      $mail->Host = 'smtp.mxhichina.com';//$email_config['MAIL_HOST'];           //smtp服务器的名称（这里以QQ邮箱为例）
      $mail->SMTPAuth = TRUE;   //启用smtp认证
      $mail->Username = $email_config['MAIL_USERNAME'];   //你的邮箱名
      $mail->Password = $email_config['MAIL_PASSWORD'];   //邮箱密码
      $mail->From = $email_config['MAIL_FROM'];           //发件人地址（也就是你的邮箱地址）
      $mail->FromName = $email_config['MAIL_FROMNAME'];   //发件人姓名
      $mail->AddAddress($to, $userName);   //
      $mail->WordWrap = 50;                   //设置每行字符长度
      $mail->IsHTML(true);        // 是否HTML格式邮件
      $mail->CharSet = "utf-8";     //设置邮件编码
      $mail->Subject = $title;                //邮件主题
      $mail->Body = $template;                //邮件内容
      $mail->AltBody = $title; //邮件正文不支持HTML的备用显示
      $res = $mail->Send();
      if($res !== true){
        // dump($res);
        // $res = array(state=>0,errormsg=>'email send failed');
        return $res;
      }
      $res = array(state=>1,errormsg=>ok);
      return $res;
    }

    private function emailSend($demand, $data){
      $path = C(CONFIG_PATH)."/email/$demand.template.html";
      $template = file_get_contents($path);
      if(!$template){
        return array(state=>0,errormsg=>'template empty');
      }
      $s = $data[title];
      $i = strpos($s,"{\$");
      while($i){
        $ii = strpos($s,"}",$i);
        $e = substr($s,$i+2,$ii-$i-2);
        if(!$data[$e]){
          return array(state=>0,errormsg=>"title needs $e");
        }
        $s = str_replace("{\$".$e."}",$data[$e],$s);
        $i = strpos($s,"{\$");
      }
      $data[title] = $s;
      // $value = $data[value];
      $s = $template;
      $i = strpos($s,'{$');
      while($i){
        $ii = strpos($s,"}",$i);
        $e = substr($s,$i+2,$ii-$i-2);
        if(!$data[$e]){
          return array(state=>0,errormsg=>"template needs $e");
        }
        $s = str_replace('{$'.$e."}",$data[$e],$s);
        $i = strpos($s,'{$');
      }
      $path = C(CONFIG_PATH)."/email/template.html";
      $public = file_get_contents($path);
      $data[template] = str_replace(__CONTENT__, $s, $public);
      $a = C('EMAIL_ACTION');
      if(!$a){
        return array(state=>0,errormsg=>"email action empty");
      }
      $res = $this->$a($demand,$data);
      return $res;
    }

    public function email($demand, $data) {
      $config = $this->getConfig('email');
      if(!$config){
        return array(state=>0,errormsg=>'config error');
      }
      $config = $config[$demand];
      if(!$config){
        return array(state=>0,errormsg=>'demand error');
      }

      //
      $cool = $config[cooldown_ip];
      if(!$cool){
        return array(state=>0,errormsg=>'ip cool error');
      }
      $cool     = explode(",",$cool);
      $during   = $cool[0];
      $limit    = $cool[1];
      $order    = "EMAIL_ID desc";
      $classId = $config[id];
      $field    = "create_time";
      // $field    = "";
      $where  = array(
        "IP_REMOTE"   => $this->getIP(),
        "CLASS" => $classId,
        );
      // dump($cool);
      // dump($where);
      // dump($limit);
      $res = M(email)->where($where)->field($field)->limit($limit-1,1)->order($order)->select();
      // dump($res);
      // dump(M()->getLastSql());
      $mostSendTime = $res[0]['create_time'];
      if($mostSendTime){
        $timePassed = time() - $mostSendTime;
        if( $timePassed < $during ){
          $remain = $during - $timePassed;
          return array(state=>0,errormsg=>'this ip send too much',data=>array(remain=>$remain));
        }
      }
      //
      $email = $data['email'];
      if(!$email){
        return array(state=>0,errormsg=>'email error');
      }
      //
      $cooldown = (int)$config[cooldown];
      $where  = array(
        "EMAIL" => $email ,
        "CLASS" => $classId ,
        );
      if(!$cooldown){
        return array(state=>0,errormsg=>'cool error');
      }
      $res = M(email)->where($where)->field($field)->order($order)->find();
      // dump($res);
      // dump(M()->getLastSql());
      $lastSendTime = $res[create_time];
      $timePassed = time() - $lastSendTime;
      if( $timePassed < $cooldown ){
        $remain = $cooldown - $timePassed;
        return array(state=>0,errormsg=>'email cooling',data=>array(remain=>$remain));
      }
      //
      $data[title] = $config[title];
      $res = $this->emailSend($demand,$data);
      if(!$res[state]){
        return $res;
      }
      $save = array(
        EMAIL       => $email,
        'CLASS'     => $config[id],
        CREATE_TIME => time(),
        IP_REMOTE   => $this->getIP()
        );
      $res = M('email')->add($save);
      return array(state=>1,errormsg=>'email send success');
    }

    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------
    // ----------------------------- QRCODE --------------------------------

    //单纯的二维码创建
    public function qrcode($url, $level = 5, $size = 10) {
      Vendor('phpqrcode'); //引用phpqrcode文件
      $errorCorrectionLevel = intval($level); //容错级别 intval()函数变量转换整形
      $matrixPointSize = intval($size); //生成图片大小 
      //生成二维码图片 
      //echo $_SERVER['REQUEST_URI'];
      $object = new \QRcode();
      $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    }


    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    // ----------------------------- SMS --------------------------------
    //短信，调用百度API
    private function smsSend_baidu($demand,$data){//,$phoneNumber, $templateCode, $contentVar) {
      $need = explode(",",$data[need]);//array(template_id,value,tel);
      foreach ($need as $value) {
        if(!$data[value][$value]){
          return array(state=>0,errormsg=>"value $value missing",data=>$data[value]);
        }
      }
      $templateCode   = $data[template_id];
      $phoneNumber    = $data[tel];
      $contentVar     = $data[value];
      //$content      = $data['content'];
      $config_baidu = C("SMS_BAIDU");
      $profileCode  = $config_baidu['PROFILE_CODE'];
      $apikey       = $config_baidu['API_KEY'];
      // $apikey = '38d5cdf9d5c694e454f6e5f4239a75a2';
      $url = 'http://apis.baidu.com/baidu_communication/baidusms/baidusms?profileCode=' . $profileCode . '&phoneNumber=' . $phoneNumber . '&templateCode=' . $templateCode;
      $contentVar = json_encode($contentVar);  //必须是json串
      $contentVar = urlencode($contentVar);   //必须经过urlencode编码

      $url .= '&contentVar=' . $contentVar;
      $ch = curl_init();

      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_HEADER, FALSE);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array("apikey: $apikey"));
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

      $response = curl_exec($ch);
      $response = json_decode($response,1);
      if (curl_errno($ch)) {
        return array(state=>0,errormsg=>'curl error',data=>array(curl_errno=>curl_errno($ch)));
          //throw curl_errno($ch);
          //throw new Exception('请求apistore失败!', self::CURL_ERROR);
      }
      curl_close($ch);
      if($response[code] == '1000'){
        $res = array(state=>1);
      }else{
        $res = array(state=>0,errormsg=>$response[message],data=>$response);
      }
      return $res;
    }

    private function smsSend_smscn($demand,$data){
      $config = $this->getConfig(sms)[$demand];
      $account = C(SMS_ACCOUNT);
      $pwd = C(SMS_SECRET);
      $template_id = $data[english]?$config[template_id_en]:$config[template_id];
      $tel = $data[tel];
      $content_array = $data[content];
      $content = json_encode($content_array);
      $postFields = array(
        ac=>send,
        uid=>$account,
        pwd=>$pwd,
        template=>$template_id,
        mobile=>$tel,
        content=>$content
        // format => json,
        );
      // $url = "http://api.sms.cn/sms/?ac=number&uid=bachnewton&pwd=117e8a34717470694f994e9d0e2e5508";
      // $url = "http://api.sms.cn/sms/?ac=send&uid=$account&pwd=$pwd&template=$template_id&mobile=$tel&content=$content";
      $url = "http://api.sms.cn/sms/";
      $postFields = http_build_query($postFields);
      // dump($url);
      // dump($postFields);
      // echo $url.'?'.$postFields;
      $ch = curl_init ();
      curl_setopt ( $ch, CURLOPT_POST, 1 );
      curl_setopt ( $ch, CURLOPT_HEADER, 0 );
      curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
      curl_setopt ( $ch, CURLOPT_URL, $url );
      curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postFields );
      $result = curl_exec ( $ch );
      curl_close ( $ch );
      // dump($result);
      if( mb_detect_encoding($result,array('ASCII','UTF-8','GB2312','GBK')) != 'UTF-8' )
      {
        $result = iconv('GBK','UTF-8',$result);
      }
      $result = json_decode($result,true);
      // dump($result);
      if($result[stat] != "100"){
        $ret = array(state=>0,errormsg=>"sms error ".$result[message],errorcode=>$result[stat]);
        return $ret;
      }
      $ret = array(state=>1);
      return $ret;

    }
    //sih接口
    private function smsSend_hongyanche($demand,$data){
      //检查基本数据
      $need = array(value,tel);
      foreach ($need as $value) {
        if(!$data[$value]){
          return array(state=>0,errormsg=>"$value missing");
        }
      }
      $config = $this->getConfig('sms');
      $config = $config[$demand];
      //放置数据 将value中的内容放入content中
      $value = $data[value];
      $s = $config[content];
      $i = strpos($s,"{");
      while($i){
        $ii = strpos($s,"}");
        $e = substr($s,$i+1,$ii-$i-1);
        if(!$value[$e]){
          return array(state=>0,errormsg=>"sms value needs $e");
        }
        $s = str_replace("{".$e."}",$value[$e],$s);
        $i = strpos($s,"{");
      }
      $content = $s;
      //return array(state=>1,errormsg=>"ok");
      $tel = $data['tel'];
      //$content = $data[content];
      //开始启用hongyanche肥皂结构发送
      header("content-type:text ml;charset=utf-8");
      $client = new \SoapClient("http://ws.sih.cq.cn/sihwebservice/message/SAPMessageService.asmx?wsdl");
      //$content = "工程师系统测试 hello world";
      $send = array(
        'key'=>"89418D76-0BB7-4311-B8EC-C3B79F6978C0",
        'Message'=>array(
          'Items'=> array(
            'ReciveMessge'=>array(
              'Content'=>$content,
              'PhoneNo'=>$tel
              ),
            )
          )
        );
      $return = $client->SendMessage($send);
      $return = json_decode(json_encode($return),1);
      $reason = $return[SendMessageResult][reason];
      if( strstr($reason,$tel) ){
        $ret = array(state=>1,errormsg=>'sms send success');
      }else{
        $ret = array(state=>0,errormsg=>$reason,data=>$return);

      }
      return $ret;
    }
    //选择调用哪一个
    private function smsSend($demand,$data){
      $a = C('SMS_ACTION');
      $res = $this->$a($demand,$data);
      return $res;
      //$this->smsSend_hongyanche();
    }
    //冷却时间查询
    public function smsCooldown($demand,$data){
      $config = $this->getConfig('sms');
      if(!$config){
        return array(state=>0,errormsg=>'config error');
      }
      $config = $config[$demand];
      // dump($config);
      if(!$config){
        return array(state=>0,errormsg=>'demand error');
      }
      $tel  = $data['tel'];
      if(!$tel){
        return array(state=>0,errormsg=>'tel error');
      }
      $classId  = $config["id"];
      //cool_tel
      $cool = $config[cooldown_tel];
      if(!$cool){
        return array(state=>0,errormsg=>'cool error');
      }
      $cool     = explode(",",$cool);
      $cooldown = $cool[0];
      $during   = $cool[1];
      $limit    = $cool[2]?$cool[2]:1;
      $order    = "SMS_ID desc";
      $where  = array(
        "TEL"   => $tel,
        "CLASS" => $classId,
        );
      // dump($cool);
      // dump($where);
      // dump($limit);
      $res = M(sms)->where($where)->limit($limit)->order($order)->select();
      // dump(M()->getLastSql());
      // dump($res);
      $lastSendTime = $res[0][create_time];
      $timePassed = time() - $lastSendTime;
      if( $timePassed < $cooldown ){
        $remain = $cooldown - $timePassed;
        return array(state=>0,errormsg=>'sms cooling',data=>array(remain=>$remain));
      }
      $mostSendTime = $res[$limit-1][create_time];
      if($mostSendTime){
        $timePassed = time() - $mostSendTime;
        if( $timePassed < $during ){
          $remain = $during - $timePassed;
          return array(state=>0,errormsg=>'sms send too much',data=>array(remain=>$remain));
        }
      }
      // dump($res);
      //cool_tel
      $cool = $config[cooldown_ip];
      if(!$cool){
        return array(state=>0,errormsg=>'ip cool error');
      }
      $cool     = explode(",",$cool);
      $during   = $cool[0];
      $limit    = $cool[1];
      $order    = "SMS_ID desc";
      $field    = "create_time";
      $where  = array(
        "IP_REMOTE"   => $this->getIP(),
        "CLASS" => $classId,
        );
      // dump($cool);
      // dump($where);
      // dump($limit);
      $res = M(sms)->where($where)->field($field)->limit($limit-1,1)->order($order)->select();
      $mostSendTime = $res[0]['create_time'];
      if($mostSendTime){
        $timePassed = time() - $mostSendTime;
        if( $timePassed < $during ){
          $remain = $during - $timePassed;
          return array(state=>0,errormsg=>'this ip send too much',data=>array(remain=>$remain));
        }
      }
      return array(state=>1,data=>'sms available');
    }
    public function sms($demand, $data) {
      //冷却时间查询
      $cool = $this->smsCooldown($demand,$data);
      if(!$cool[state]){
        return $cool;
      }
      //内容要求
      $config = $this->getConfig(sms)[$demand];
      $para = $config[template_para];
      foreach (explode(",", $para) as $key => $value) {
        if(!$data[$value]){
          return array(state=>0,errormsg=>"need $value");
        }
        $content[$value] = $data[$value];
      }
      $data[content] = $content;
      // dump($content);
      //开始发送
      $res = $this->smsSend($demand,$data);
      if(!$res[state]){
        return $res;
      }
      $userId = D(user)->getUserId();
      $tel = $data[tel];
      if($config[template_para_save]){
        $paraSave = json_encode($content);
      }
      $add = array(
        TEL           => $tel,
        'CLASS'       => $config[id],
        CREATE_TIME   => time(),
        IP_REMOTE     => $this->getIP(),
        USER_ID       => $userId,
        TEMPLATE_PARA => $paraSave,
        );
      M('sms')->add($add);
      $cool = $config[cooldown_tel];
      $cool_time = explode(",",$cool)[0];
      return array(state=>1,errormsg=>'sms send success',data=>array(remain=>$cool_time));      
    }
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------
    // ------------------------ VERIFY -----------------------

    //创建验证码
    public function verifyCreate() {
      $Verify = new \Think\Verify();
        $Verify->fontSize = 46; //验证码字体大小
        $Verify->length = 4;
        $Verify->entry();
      }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
      public function verifyCheck($code, $id = '') {
        $verify = new \Think\Verify();
        $a = $verify->check($code, $id);
        if (!$a) {
          return array('state' => 0, 'errormsg' => 'verify error');
        }
        return array('state' => 1);
      }

    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    // ------------------------ EXCEL -----------------------
    //最简单的创建excel（没有sheet和标题）控制器调用的是这个方法
      public function excelSimple($data) {
        $arr = $data['filecontent'];
        $d = array();
        foreach ($arr[0] as $k => $v) {
          $d[$k] = strtoupper($k);
        }
        array_unshift($arr, $d);
        if (!empty($arr)) {
          foreach ($arr as $key => $val) {
            $arr[$key] = implode("\t", $arr[$key]);
          }
          echo implode("\n", $arr);
        }
        $filename = $data['filename'];
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //告诉浏览器输出2007excel
        header("Content-Disposition:attachment;filename=" . $filename . ".xls"); //告诉浏览器输出的文件名
        header('Cache-Control: max-age=0'); //禁止缓存
        header("Pragma: no-cache");
        header("Expires: 0");
      }
    //获取ip
      private function getIP() {
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
          $cip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
          $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
          $cip = $_SERVER["REMOTE_ADDR"];
        } else {
          $cip = false;
        }
        return $cip;
      }
    //获取省市区
      public function getIpData() {
        $apikey = C('BAIDU_API_KEY');
        $ip = $this->getIP();
        $ch = curl_init();
        $url = "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=$ip";
        // $url = "http://api.sms.cn/sms/";
        $header = array(
          "apikey: $apikey",
          );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch, CURLOPT_URL, $url);
        $res = curl_exec($ch);
        curl_close ( $ch );
    //var_dump($ip,$url,$res);
        
        return json_decode($res, true);
      }

    //根据省会获取坐标
      private function coordinate($province){
        $file = file_get_contents('config/support-location.config.json');
        $file =  json_decode($file,1);
        $result = $file[$province];
        $res = explode(',', $result);
        return $res;
      }

    }
